package dimension.starry.dataManager;

import net.minecraft.nbt.NbtCompound;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;

public class LootChestDataManager {

    private static final String LOOT_DATA_KEY = "lootData";

    private static NbtCompound getSingleLootData(ServerWorld world, BlockPos blockPos) {
        return getLootDataFromManager(world).getCompound(getLootPosKey(world, blockPos));
    }

    public static boolean containsAndAddPlayerIfAbsent(ServerWorld world, BlockPos blockPos, String playerName) {
        NbtCompound singleLootData = getSingleLootData(world, blockPos);
        if (singleLootData.contains(playerName)) {
            return true;
        } else {
            singleLootData.putLong(playerName, System.currentTimeMillis());
            setSingleLootData(world, singleLootData, blockPos);
            return false;
        }
    }

    private static NbtCompound getLootDataFromManager(ServerWorld world) {
        NbtCompound NbtCompound = DataManager.getNbt(world, LOOT_DATA_KEY);
        if (NbtCompound == null) {
            NbtCompound = new NbtCompound();
            DataManager.setNbt(world, LOOT_DATA_KEY, NbtCompound);
        }
        return NbtCompound;
    }

    private static void setSingleLootData(
        ServerWorld world, NbtCompound lootNbt, BlockPos blockPos
    ) {
        NbtCompound nbtCompound = getLootDataFromManager(world);
        nbtCompound.put(getLootPosKey(world, blockPos), lootNbt);
        DataManager.setNbt(world, LOOT_DATA_KEY, nbtCompound);
    }

    private static String getLootPosKey(ServerWorld world, BlockPos blockPos) {
        return world.getSeed() + "_" + blockPos.getX() + "_" + blockPos.getY() + "_" + blockPos.getZ();
    }

}
